<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />

    

    

    <title>redisson分布式锁 | 郑礼德技术栈</title>
    <meta name="author" content="郑礼德" />
    <meta name="keywords" content="" />
    <meta name="description" content="分布式系统设计中在高并发多个微服务的场景下，常常会因为在做更新操作时多个服务操作同一条数据，而导致数据不一致性问题，此时需要分布式锁来保证数据一致性，实现分布式锁的方式有很多，zookeeper redis+lua 等，本文介绍比较常用的redisson使用redisson 作为分布式锁redisson使用可以参考文档添加依赖 &amp;lt;dependency&amp;gt;            &amp;lt;groupId&amp;gt;org.redisson&amp;lt;/groupId&amp;gt;   ..." />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />

    
    <link rel="alternate" href="/homepage/atom.xml" title="郑礼德技术栈" type="application/atom+xml">
    
    
    <link rel="icon" href="/homepage/images/favicon.ico">
    

    <style type="text/css">
    @font-face {
        font-family: 'icomoon';
        src: url("/homepage/fonts/icomoon.eot?q628ml");
        src: url("/homepage/fonts/icomoon.eot?q628ml#iefix") format('embedded-opentype'),
             url("/homepage/fonts/icomoon.ttf?q628ml") format('truetype'),
             url("/homepage/fonts/icomoon.woff?q628ml") format('woff'),
             url("/homepage/fonts/icomoon.svg?q628ml#icomoon") format('svg');
        font-weight: normal;
        font-style: normal;
    }
    </style>
    
<link rel="stylesheet" href="/homepage/css/style.css">


    <!--[if lt IE 9]>
    <style type="text/css">
    .nav-inner {top:0;}
    .author-meta {position:static;top:0;}
    .search-form {height:36px;}
    </style>
    <script type="text/javascript" src="https://unpkg.com/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
    <![endif]-->
<meta name="generator" content="Hexo 4.2.0"></head>
<body>

    <main class="app">
        <header id="header" class="header clearfix">
    <div id="nav" class="nav">
    <div class="nav-mobile">
        <button id="open-panel" class="open-panel nav-mobile-item"><i class="icon-documents"></i></button>
        <h1 class="nav-mobile-title nav-mobile-item">郑礼德技术栈</h1>
        <button id="open-menus" class="open-panel nav-mobile-item"><i class="icon-library"></i></button>
    </div>

    <nav id="nav-inner" class="nav-inner">
        
            <a class="nav-item" href="/homepage/">
                <span class="nav-text">首页</span>
            </a>
        
            <a class="nav-item" href="/homepage/categories/front-end">
                <span class="nav-text">前端</span>
            </a>
        
            <a class="nav-item" href="/homepage/categories/back-end">
                <span class="nav-text">后端</span>
            </a>
        
            <a class="nav-item" href="/homepage/categories/linux">
                <span class="nav-text">linux部署</span>
            </a>
        
            <a class="nav-item" href="/homepage/tags">
                <span class="nav-text">标签</span>
            </a>
        
            <a class="nav-item" href="/homepage/archives">
                <span class="nav-text">归档</span>
            </a>
        
            <a class="nav-item" href="/homepage/about">
                <span class="nav-text">关于</span>
            </a>
        
    </nav>
</div>

    <aside id="aside" class="aside">
    <div id="aside-mask" class="aside-mask"></div>
    <div id="aside-inner" class="aside-inner">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit"><i class="icon-search-stroke"></i></button><input type="hidden" name="sitesearch" value="http://zhenglide.gitee.io/homepage"></form>

        
        
        
        

        
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#使用redisson-作为分布式锁"><span class="toc-number">1.</span> <span class="toc-text">使用redisson 作为分布式锁</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#添加依赖"><span class="toc-number">1.1.</span> <span class="toc-text">添加依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#添加redison-配置"><span class="toc-number">1.2.</span> <span class="toc-text">添加redison 配置</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#redisson-使用"><span class="toc-number">1.3.</span> <span class="toc-text">redisson 使用</span></a></li></ol></li></ol>
        
    </div>
</aside>

</header>

        <div id="content" class="content">
            <div id="wrapper" class="wrapper" style="max-width: 800px">
                <article class="article" itemscope itemprop="blogPost">
    
    <header class="article-header">
        
        <h1 itemprop="name">
            redisson分布式锁
        </h1>
        
        <div class="article-meta clearfix">
            <a class="article-date" href="http://zhenglide.gitee.io/homepage/2020/10/29/redisson%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/index.html">
    
    <i class="icon-calendar"></i>
    
    <time datetime="2020-10-29T08:02:40.000Z" itemprop="datePublished">2020-10-29</time>
</a>

            
<div class="article-tag-list">
    <i class="icon-tag"></i>
    <a class="article-tag-link" href="/homepage/tags/redis/" rel="tag">redis</a>, <a class="article-tag-link" href="/homepage/tags/%E5%88%86%E5%B8%83%E5%BC%8F/" rel="tag">分布式</a>
</div>


        </div>
    </header>
    
    <section class="article-body markdown-body">
        
        <p>分布式系统设计中在高并发多个微服务的场景下，常常会因为在做更新操作时多个服务操作同一条数据，而导致数据不一致性问题，此时需要分布式锁来保证数据一致性，实现分布式锁的方式有很多，zookeeper redis+lua 等，本文介绍比较常用的redisson</p>
<a id="more"></a>

<h2 id="使用redisson-作为分布式锁"><a href="#使用redisson-作为分布式锁" class="headerlink" title="使用redisson 作为分布式锁"></a>使用redisson 作为分布式锁</h2><p>redisson使用可以参考<a href="https://github.com/redisson/redisson/wiki/%E7%9B%AE%E5%BD%95" target="_blank" rel="noopener">文档</a></p>
<h3 id="添加依赖"><a href="#添加依赖" class="headerlink" title="添加依赖"></a>添加依赖</h3><pre><code class="xml"> &lt;dependency&gt;
            &lt;groupId&gt;org.redisson&lt;/groupId&gt;
            &lt;artifactId&gt;redisson&lt;/artifactId&gt;
            &lt;version&gt;3.6.5&lt;/version&gt;
  &lt;/dependency&gt;</code></pre>
<h3 id="添加redison-配置"><a href="#添加redison-配置" class="headerlink" title="添加redison 配置"></a>添加redison 配置</h3><p>实际使用最好写在配置文件中</p>
<p>1.哨兵模式</p>
<pre><code class="java">
@Configuration
public class RedissonConfig {
    /**
     *
     *  哨兵模式
     * @return
     */
    @Bean
    public Redisson sentinelClient(){
        Config config =new Config();
        config.useSentinelServers()
                .setMasterName(&quot;mymaster&quot;)
                .addSentinelAddress(&quot;redis://192.168.1.128:26378&quot;,&quot;redis://192.168.1.128:26379&quot;,&quot;redis://192.168.1.128:26377&quot;);
        return (Redisson) Redisson.create(config);
    }


}

</code></pre>
<p>2.单机模式</p>
<pre><code class="java">@Configuration
public class RedissonConfig {
  /**
     * 单机模式
     * @return
     */
    @Bean
    public Redisson singlelClient(){
        Config config =new Config();
        config.useSingleServer()
                .setAddress(&quot;redis://192.168.1.128:6379&quot;)
                .setDatabase(0);
        return (Redisson) Redisson.create(config);
    }


}</code></pre>
<h3 id="redisson-使用"><a href="#redisson-使用" class="headerlink" title="redisson 使用"></a>redisson 使用</h3><pre><code class="java">@RestController
public class IndexController {

   @Autowired
    StringRedisTemplate stringRedisTemplate;
   @Autowired
   Redisson redisson;
    @RequestMapping(&quot;/deduct_stock&quot;)
    public String deductStock() {
//          lock.lock();
        RLock lock = redisson.getLock(&quot;lock&quot;);
        lock.lock(30, TimeUnit.SECONDS);
          try {
              int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get(&quot;stock&quot;));
              if(stock &gt; 0) {
                  Integer newStock = stock -1;

                  stringRedisTemplate.opsForValue().set(&quot;stock&quot;,newStock.toString());
                  System.out.println(&quot;扣减成功，当前库存&quot; + newStock);
              }else {
                  System.out.println(&quot;库存不足，扣减失败&quot;);
                  return  &quot;扣减失败&quot;;
              }

          }finally {
             lock.unlock();
          }
        return  &quot;扣减成功&quot;;
    }
}</code></pre>
<p>1.注入redisson实例</p>
<p>2.使用以下固定代码实现</p>
<pre><code class="java">     RLock lock = redisson.getLock(&quot;lock&quot;);
        lock.lock(30, TimeUnit.SECONDS);
          try {
             //业务逻辑
          }finally {
             lock.unlock();
          }</code></pre>
<p>至此分布式锁就实现了</p>

        
    </section>
</article>



<a id="pagenext" href="/homepage/2020/10/29/redis%E4%B8%BB%E4%BB%8E%E6%A8%A1%E5%BC%8F%E5%8F%8A%E5%93%A8%E5%85%B5%E6%A8%A1%E5%BC%8F/" class="article-next" title="redis主从模式及哨兵模式"><i class="icon-arrow-right"></i></a>





            </div>
        </div>
        <footer class="footer">
    Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>, Theme by <a href="https://github.com/sanonz/hexo-theme-concise" target="_blank">Concise</a>

    
    <script>
        var _hmt = _hmt || [];
        (function () {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?b13bb4c2ef8300062aab9732bd22eae0";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>
    
</footer>

    </main>

    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.9.0/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
        var nodes = {
            nav: $('#nav'),
            aside: $('#aside'),
            asideInner: $('#aside-inner'),
            navInner: $('#nav-inner')
        };

        var doing = false;
        nodes.asideInner.on('webkitAnimationEnd mozAnimationEnd oAnimationEnd oanimationend animationend', function() {
            if (nodes.aside.hasClass('mobile-open')) {
                nodes.aside.removeClass('mobile-open');
            } else {
                nodes.aside.removeClass('mobile-close panel-show');
            }
            doing = false;
        });
        $('#open-panel, #aside-mask').on('click', function() {
            if (doing) {
                return;
            }

            if (nodes.aside.hasClass('panel-show')) {
                nodes.aside.addClass('mobile-close');
            } else {
                nodes.aside.addClass('mobile-open panel-show');
            }
        });
        $('#open-menus').on('click', function() {
            nodes.navInner.slideToggle();
        });

        if (window.innerWidth <= 960) {
            setTimeout(function() {
                nodes.navInner.slideUp();
            }, 3000);
        }
    });
    </script>
    
        
<script src="/homepage/js/scrollspy.min.js"></script>

        <script type="text/javascript">
        $(document.body).scrollspy({target: '#aside-inner'});

        $(window).on('resize', function() {
            var hw = $('#header').width();
            var ww = $('#wrapper').width();
            var space = ($(this).width() - hw - ww) / 2 / 2;

            var pageprev = $('#pageprev');
            var pagenext = $('#pagenext');
            var avg = (pageprev.width() + pagenext.width()) / 2

            if(space > avg) {
                var len = space - avg / 2;
                var styles = {position: 'fixed', top: '50%', marginTop: - (pageprev.width() + pagenext.width()) / 4}
                pageprev.css($.extend({left: hw + len}, styles));
                pagenext.css($.extend({right: len}, styles));
            } else {
                pageprev.removeAttr('style');
                pagenext.removeAttr('style');
            }
        }).trigger('resize');
        </script>
    

</body>
</html>
